package org.bes.WinClass;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
public class PatchInfo {
    private String patchName;
    private String patchVersion;
    private String mainClass;



    public PatchInfo() {
    }

    public String getPatchName() {
        return patchName;
    }

    public void setPatchName(String patchName) {
        this.patchName = patchName;
    }

    public void setMainClass(String mainClass) {
        this.mainClass = mainClass;
    }

    public String getPatchVersion() {
        return patchVersion;
    }

    public void setPatchVersion(String patchVersion) {
        this.patchVersion = patchVersion;
    }

    //根据已解压文件的类型，对应获取脚本信息，目前考虑jar与js文件，****后续此处考虑更新其他文件****
    public PatchInfo getPatchInfo(File file) throws IOException {
        if(!file.exists() && !file.isFile()) {
            System.out.println("file does not exist or is invalid: " + file.getAbsolutePath());
            return this;
        }

        if (file.getName().endsWith(".jar")) {
            setPatchName(file.getName());
            readJarMetadata(Path.of(file.getAbsolutePath()));
        }

        return this;
    }

    //读取jar文件的manifest.mf当中的信息
    public void readJarMetadata(Path jarPath) throws IOException {
        //System.out.println(jarPath);

        try (JarFile jar = new JarFile(String.valueOf(jarPath))) {
            Manifest manifest = jar.getManifest();
            if (manifest != null) {
                //获取manifest中的jar包信息
                Attributes mainAttributes = manifest.getMainAttributes();
                String mainClass = mainAttributes.getValue(Attributes.Name.MAIN_CLASS);
                String manifestVersion = mainAttributes.getValue(Attributes.Name.MANIFEST_VERSION);
                setPatchVersion(manifestVersion != null ? manifestVersion : "N/A");
                setMainClass(mainClass != null ? mainClass : "N/A");

                //System.out.println("Main Class: " + (mainClass != null ? mainClass : "N/A"));
                //System.out.println("Manifest Version: " + (manifestVersion != null ? manifestVersion : "N/A"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
